import logging
from logging.handlers import RotatingFileHandler
import os


def setup_logging():
    # 获取根logger
    logger = logging.getLogger()

    # 清除已存在的处理器，避免重复添加
    logger.handlers.clear()

    logger.setLevel(logging.DEBUG)  # 设置为最低级别以捕获所有日志

    # 创建格式器
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )

    # 创建logs目录
    log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs")
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    # 错误日志处理器 (ERROR及以上级别)
    error_handler = RotatingFileHandler(
        os.path.join(log_dir, "error.log"),
        maxBytes=1024 * 1024 * 10,  # 10MB
        backupCount=5,
        encoding='utf-8'
    )
    error_handler.setLevel(logging.ERROR)
    error_handler.setFormatter(formatter)
    logger.addHandler(error_handler)

    # 信息日志处理器 (INFO级别，排除ERROR及以上)
    info_handler = RotatingFileHandler(
        os.path.join(log_dir, "info.log"),
        maxBytes=1024 * 1024 * 10,  # 10MB
        backupCount=5,
        encoding='utf-8'
    )
    info_handler.setLevel(logging.INFO)
    info_handler.setFormatter(formatter)
    # 添加过滤器，只记录INFO和WARNING级别（排除ERROR及以上）
    info_handler.addFilter(lambda record: record.levelno < logging.ERROR)
    logger.addHandler(info_handler)

    # 调试日志处理器 (DEBUG级别)
    debug_handler = RotatingFileHandler(
        os.path.join(log_dir, "debug.log"),
        maxBytes=1024 * 1024 * 10,  # 10MB
        backupCount=5,
        encoding='utf-8'
    )
    debug_handler.setLevel(logging.DEBUG)
    debug_handler.setFormatter(formatter)
    # 添加过滤器，只记录DEBUG级别
    debug_handler.addFilter(lambda record: record.levelno == logging.DEBUG)
    logger.addHandler(debug_handler)

    # 控制台处理器 (显示INFO及以上级别)
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)